<?php
/**
 * @file
 * All front end related stuff
 */

/**
 * Implementation of hook_view().
 */
function race_view($node, $view_mode=NULL) {
  drupal_add_css('modules/race/race.css', array('preprocess' => FALSE));
  switch ($node->state) {
    case Constants::$STATE_SIGNUP:
	    $addition = race_view_signup($node);
      break;
    case Constants::$STATE_ASSIGNMENT:
      $addition = race_view_assigned($node);
	    break;
	default:
      var_dump($node);
      throw new Exception("Unknown state type in node: ".$node->state);
  }

  if (isset($node->content)) {
    $node->content = array_merge($node->content, $addition);
  } 

  return $node;
}

/**
 * Displays the form for the user during signup phase.
 *
 * @return a renderable array (see http://drupal.org/node/930760)
 */
function race_view_signup($node) {
    global $user;
    $signups = _get_signups($node);
    $config = _get_config($node);
    
    // signup form or status
    if (!user_access('modify race')) {
      $markup = t("You can not sign up for the race unless you're logged in.")." ";
      $markup .= "<a href='".base_path()."user/login'>".t('login')."</a> / <a href='".base_path()."user/register'>".t('register')."</a>";
      $output['signup']['#markup']  = $markup;
    } else if (_is_user_signed_up($signups, $user->name)) {
      $markup = t("You are signed up for the race");
      $markup .= " (<a href='". base_path() ."race/signoff/". $node->nid ."'>".t("sign off")."</a>)";
      $output['signup']['#markup']  = $markup;
    } else if (user_access("modify race")) {
      $output['signup'] = drupal_get_form('race_sign_on', $node);
    }
    $output['signup']['#weight'] = 2;
    
    // signup list
    $output['list'] = array(
      '#title' => t("Sign up list").":",
      '#items'  => _signuplist_user($signups),
      '#theme' => 'item_list',
      '#weight' => 3
    );
	
	return $output;
}

/**
 * Displays the form for the normal user during assignmend phase.
 *
 * @return a renderable array (see http://drupal.org/node/930760)
 */
function race_view_assigned($node) {
  global $user;
  $assignments = _get_assignments($node);
  $config = _get_config($node);
  $signups = _get_signups($node);
   
  $output['assignmentlist'] = array(
    '#markup' => _assignmentlist_user($assignments, $config, $signups, $node->nid),
    '#weight' => 1
  );
  
  $output['key'] = array(
    '#markup' => _get_key_stati(),
    '#weight' => 2
  );
  
  $output['clubs'] = array(
    '#markup' => _get_key_clubs($config),
    '#weight' => 3
  );

  return $output;
}

/**
 * sign on form
 */
function race_sign_on($form, &$form_state, $node) {

  $config = _get_config($node);
  
  $form['description']['#title'] = t("You are not signed up for the race. Sign up now:");
  $form['description']['#type'] = "item";
  
  $form['#type'] = 'fieldset';
  $form['#collapsible'] = FALSE;
  $form['#collapsed'] = FALSE;
  
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $node->nid,
  );
  
  foreach ($config->form->option as $formElement) {
    $a = $formElement->attributes();
    if ($a['type'] == "textarea") {
      $id = (String) $a['id'];
      $form[$id] = array(
        '#type' => 'textarea',
        '#rows' => $a['rows'],
        '#maxlength' => $a['maxlength'],
        '#description' => $a['description'],
        '#title' => $a['title'],
      );
    }
    if ($a['type'] == "checkbox") {
      $id = (String) $a['id'];
      $form[$id] = array(
        '#type' => 'checkbox',
        '#default_value' => 0,
        '#title' => $a['title'],
        '#description' => $a['description'],
      );
    }
    if ($a['type'] == "boatselect") {
      $form["boatselect"] = array(
        '#type' => 'select',
        '#title' => $a['title'],
        '#description' => $a['description'],
        '#options' => _get_boats_options($config),
      );    
    }
    if ($a['type'] == "experience") {
      $form["experience"] = array(
        '#type' => 'radios',
        '#title' => $a['title'],
        '#description' => $a['description'],
        '#options' => _get_experience_options($formElement),
      );    
    }
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Sign up")
  );
  
  return $form;
}

function _get_boats_options($config) {
  $out[0] = t("---");
  foreach (_get_boats($config) as $key => $result) {
    $id = (string) $result['id'];
    $out[$id] = (string) $result['name'];
  }
  return $out;
}

function _get_experience_options(SimpleXMLElement $experience) {
  $out = array();
  foreach ($experience->choice as $choice) {
    $out[] = (String) $choice;
  }
  return $out;
}


/** 
 * Form validation handler for race_sign_on form.
 */
function race_sign_on_validate($form, &$form_state) {
}

/** 
 * Form submit handler for race_sign_on form.
 */
function race_sign_on_submit($form, &$form_state)
{ 
  $nid = $form_state["values"]["nid"];
  _sign_on($nid, $form_state["values"]);
  drupal_set_message(t('Your form has been submitted'));
  $form_state['redirect'] = 'node/'.$nid;
}

function _signuplist_user($signups) { 
  $users = array();
  foreach ($signups->user as $user) {
    $users[] = (String) $user->name;
  }
  return $users;
}

function _assignmentlist_user(SimpleXMLElement $assignments, SimpleXMLElement $config, SimpleXMLElement $signups, $nid) { 
  global $user;
  $html = "";
  foreach (_get_boats($config) as $boatConfig) {
    $club = $boatConfig['club'];
    $html .= "<div class='boat $club'>";
    $html .= "<div class='boatname'>".$boatConfig['name']."</div>";
    $assignees = _get_boat_assignments_by_id($assignments, $boatConfig['id']);
    for ($i=0; $i<(int)$boatConfig['places']; $i++) {
      if (sizeof($assignees) > $i) {
        $userName = $assignees->signup[$i]["user"];
        $html .= "<div class='place belegt'>";
        $html .= $userName." ";
        $html .= _get_experience($signups, $userName);
        if (user_access('admin race') || $user->name == $userName) {
          $html .= _get_link_signoff_from_boat($nid, $boatConfig['id'])." ";
        }
        $html .= "</div>";
      } else {
        $html .= "<div class='place frei'>";
        if (user_access('modify race')) {
          $html .= _get_link_signup_for_boat($nid, $boatConfig['id']);
        } else {
          $html .= "&nbsp;";
        }
        $html .= "</div>";
      }
    }
    $html .= "</div>";
  }
  return $html;
}

function _xsl($xmlString, DOMDocument $xsl) {
  $xml = new DOMDocument();
  $xml->loadXML($xmlString);
  
  $processor = new XSLTProcessor();
  $processor->importStyleSheet($xsl);
    
  return $processor->transformToXML($xml);
}

function _get_key_stati() {
  return "<table class='key'>
		<tbody><tr><th>Stati</th><th> </th></tr>
		<tr><td class='belegt'> </td><td>belegt</td></tr>
		<tr><td class='frei'> </td><td>frei</td></tr>
		</tbody></table>";
}

function _get_key_clubs(SimpleXMLElement $config) {
  $html = "<table class='key'><tr><th>Clubs</th><th></th></tr>";
  $clubs = _get_clubs($config);
  foreach ($clubs as $club) {
    $html .= "<tr><td class='$club'></td><td>$club</td></tr>";
  }
  $html .= "</table>";
  return $html;	
}

function _get_link_signup_for_boat($nid, $boatId) {
  return "<a href='".base_path()."race/signup_boat/".$nid."/".$boatId."'>".t("sign up")."</a>";
}

function _get_link_signoff_from_boat($nid, $boatId) {
  return "<a href='".base_path()."race/signoff_boat/".$nid."/".$boatId."'>".t("sign off")."</a>";
}